package com.jingyanzi.member.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.channel.domain.ChannelDO;
import com.jingyanzi.channel.domain.ChannelTypeDO;
import com.jingyanzi.channel.domain.ChannelWindowDO;
import com.jingyanzi.member.api.ChannelClientAPI;
import com.jingyanzi.member.api.DicClientAPI;
import com.jingyanzi.member.api.EmployeeClientAPI;
import com.jingyanzi.member.dao.MCustomerFamilyMapper;
import com.jingyanzi.member.dao.MCustomerMapper;
import com.jingyanzi.member.dao.MLeadLoseMapper;
import com.jingyanzi.member.dao.MLeadMapper;
import com.jingyanzi.member.domain.CustomerDO;
import com.jingyanzi.member.domain.CustomerFamilyDO;
import com.jingyanzi.member.domain.EmployeeDO;
import com.jingyanzi.member.domain.LeadDO;
import com.jingyanzi.member.domain.LeadLoseDO;
import com.jingyanzi.member.domain.SaleContactRecordDO;
import com.jingyanzi.member.domain.SchedulingDO;
import com.jingyanzi.member.domain.result.ResultDO;
import com.jingyanzi.member.domain.result.ResultSupport;
import com.jingyanzi.member.entity.MCustomer;
import com.jingyanzi.member.entity.MCustomerFamily;
import com.jingyanzi.member.entity.MLead;
import com.jingyanzi.member.entity.MLeadExample;
import com.jingyanzi.member.entity.MLeadExample.Criteria;
import com.jingyanzi.member.entity.MLeadLose;
import com.jingyanzi.member.entity.MLeadLoseExample;
import com.jingyanzi.member.query.CustomerQueryDO;
import com.jingyanzi.member.query.LeadQueryDO;
import com.jingyanzi.member.query.SaleContactRecordQueryDO;
import com.jingyanzi.member.query.SchedulingQueryDO;
import com.jingyanzi.member.service.IAnalysisService;
import com.jingyanzi.member.service.ICustomerFamilyService;
import com.jingyanzi.member.service.ICustomerService;
import com.jingyanzi.member.service.ISalesRecordService;
import com.jingyanzi.member.service.ISchedulingService;
import com.jingyanzi.member.util.BeanUtilsExtends;
import com.jingyanzi.member.util.MemberConstant;
import com.jingyanzi.member.util.StaticDicUtil;

import com.jingyanzi.sys.domain.DictionariesDO;
import com.sun.org.apache.xerces.internal.dom.DeferredDOMImplementationImpl;

@Service("analysisService")
public class AnalysisServiceImpl extends BaseServiceImpl implements IAnalysisService {

	@Autowired
	private MLeadMapper leadMapper;
	@Autowired
	private MCustomerMapper customerMapper;
	@Autowired
	private MCustomerFamilyMapper customerFamilyMapper;

	@Autowired
	private MLeadLoseMapper leadLoseMapper;

	@Autowired
	private DicClientAPI dicClientAPI;

	@Autowired
	private ChannelClientAPI channelClientAPI;

	@Autowired
	private EmployeeClientAPI employeeClientAPI;

	@Autowired
	private ISchedulingService schedulingService;

	@Autowired
	private ICustomerService customerService;

	@Autowired
	private ICustomerFamilyService customerFamilyService;

	@Autowired
	private ISalesRecordService salesRecordService;

	@Override
	public ResultDO add(LeadDO domain) {

		MLead entity = new MLead();
		ResultDO result = BeanUtilsExtends.copy(entity, domain);

		if (!result.isSuccess()) {
			result.setSuccess(false);
			return result;
		}

		MCustomer customer = customerMapper.selectByPrimaryKey(domain.getCustomerId());
		if (customer == null) {
			result.setSuccess(false);
			result.setErrorMsg("客户信息不存在");
			return result;
		}
		entity.setProvince(customer.getProvince());
		entity.setCity(customer.getCity());
		entity.setDistrict(customer.getDistrict());

		// 生日
		MCustomerFamily customerFamily = customerFamilyMapper.selectByPrimaryKey(domain.getBusinessFamilyID());
		if (customerFamily == null) {
			result.setSuccess(false);
			result.setErrorMsg("拍摄主体不存在");
			return result;
		}
		entity.setBirthday(customerFamily.getBirthday());

		entity.setCreatetime(Calendar.getInstance().getTime());
		entity.setModifitime(entity.getCreatetime());
		entity.setCollectorTime(entity.getCreatetime());
		entity.setIsDelete(MemberConstant.DB_ISDEL_NO);
		entity.setIsEntrust(MemberConstant.FLAG_FALSE);
		entity.setLeadNo(leadNo());
		if (domain.getStatus() == null) {
			if (isNumberInValid(domain.getSaleEmployeeId())) {
				// 未分配
				entity.setStatus(MemberConstant.LEAD_STATUS_NEW);
			} else {
				// 已分配
				entity.setStatus(MemberConstant.LEAD_STATUS_NO_CONTACT);
			}
		}
		if (StringUtils.isNotEmpty(domain.getSpecialComment())) {
			entity.setIsSpecial(MemberConstant.FLAG_TRUE);
		}
		if (null == domain.getOppValue() || domain.getOppValue().compareTo(new BigDecimal(0)) <= 0) {
			entity.setOppValue(null);
		}
		entity = getEntity(entity, domain);

		int r = -1;
		try {
			r = leadMapper.insertSelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			r = -1;
		}

		if (r < 0) {
			result.setSuccess(false);
		}

		// 添加跟进记录
		SaleContactRecordDO recordDO = new SaleContactRecordDO();
		recordDO.setLeadId(entity.getId());
		recordDO.setCustomerId(entity.getCustomerId());
		recordDO.setContactId(entity.getCustomerFamilyId());
		recordDO.setEmployeeId(domain.getAuthorId());
		recordDO.setEmployeeName(domain.getAuthor());
		if (isNumberInValid(domain.getSaleEmployeeId())) {
			// 收集
			recordDO.setTopic("创建线索");
		} else {
			// 已分配
			recordDO.setTopic("创建线索并分配");
		}
		recordDO.setRemark(entity.getRemark());
		recordDO.setNextDateStamp(domain.getFollowNextStamp());
		salesRecordService.add(recordDO);

		// TODO： 是否已分配销售

		result.setModel(ResultSupport.FIRST_MODEL_KEY, entity);
		return result;
	}

	@Override
	public ResultDO remove(Integer[] ids) {

		ResultDO result = new ResultSupport();

		MLeadExample example = new MLeadExample();
		MLeadExample.Criteria criteria = example.createCriteria();
		criteria.andIdIn(Arrays.asList(ids));
		criteria.andIsDeleteEqualTo(MemberConstant.DB_ISDEL_NO);

		MLead entity = new MLead();
		entity.setIsDelete(MemberConstant.DB_ISDEL_YES);

		int r = -1;
		try {
			r = leadMapper.updateByExampleSelective(entity, example);
		} catch (Exception e) {
			e.printStackTrace();
			r = -1;
		}

		if (r < 1) {
			result.setSuccess(false);
		}
		return result;
	}

	@Override
	public ResultDO modifi(LeadDO domain) {
		MLead entity = new MLead();
		ResultDO result = BeanUtilsExtends.copy(entity, domain);

		if (!result.isSuccess()) {
			result.setSuccess(false);
			return result;
		}

		int r = -1;
		entity = getEntity(entity, domain);
		try {
			r = leadMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			r = -1;
		}

		if (r < 0) {
			result.setSuccess(false);
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, entity);
		return result;
	}

	@Override
	public ResultDO edit(LeadDO domain) {

		ResultDO result = new ResultSupport();

		MLead entity = leadMapper.selectByPrimaryKey(domain.getId());
		if (entity == null) {
			result.setSuccess(false);
			return result;
		}

		if (isNumberInValid(domain.getBusinessFamilyID())) {
			result.setSuccess(false);
			result.setErrorMsg("拍摄主体为空");
			return result;
		}
		entity.setId(domain.getId());
		entity.setBusinessFamilyID(domain.getBusinessFamilyID());

		entity.setIsSpecial(
				StringUtils.isEmpty(domain.getSpecialComment()) ? MemberConstant.FLAG_FALSE : MemberConstant.FLAG_TRUE);
		entity.setSpecialComment(domain.getSpecialComment());
		entity.setBirthHospital(getInteger(domain.getBirthHospital()));
		if (domain.getBirthHospital() != null) {
			entity.setBirthHospitalName(getChannelName(entity.getBirthHospital()));
		}
		entity.setIsPhoto(domain.getIsPhoto());
		entity.setNotPhotoReason(getInteger(domain.getNotPhotoReason()));

		entity.setWeddingdate(getDate(domain.getWeddingdateStamp()));
		entity.setExpectdate(getDate(domain.getExpectdateStamp()));

		entity.setChannelTypeID(getInteger(domain.getChannelTypeID()));
		entity.setChannelID(getInteger(domain.getChannelID()));
		entity.setWindowID(getInteger(domain.getWindowID()));

		entity.setNetSaleEmployeeID(getInteger(domain.getNetSaleEmployeeID()));
		entity.setNetSaleEmployeeName(getString(domain.getNetSaleEmployeeName()));

		entity.setIntrodType(getInteger(domain.getIntrodType()));
		entity.setIntroducerId(getInteger(domain.getIntroducerId()));
		entity.setIntroducerName(getString(domain.getIntroducerName()));

		entity.setCollectorEmployeeID(getInteger(domain.getCollectorEmployeeID()));
		entity.setCollectorEmployeeName(getString(domain.getCollectorEmployeeName()));

		entity.setRemark(domain.getRemark());

		entity.setStatus(domain.getStatus());

		entity.setAlloTime(getDate(domain.getAlloTimeStamp()));
		entity.setAlloEmployeeID(getInteger(domain.getAlloEmployeeID()));
		entity.setAlloEmployeeName(getString(domain.getAlloEmployeeName()));

		entity.setSaleEmployeeId(getInteger(domain.getSaleEmployeeId()));
		entity.setSaleName(getString(domain.getSaleName()));
		entity.setSaleOrgID(getInteger(domain.getSaleOrgID()));
		entity.setStoreName(getString(domain.getStoreName()));

		entity.setFollowNext(getDate(domain.getFollowNextStamp()));
		entity.setFollowTime(getDate(domain.getFollowTimeStamp()));

		entity.setOppType(getInteger(domain.getOppType()));
		entity.setOppTypeName(getString(domain.getOppTypeName()));
		entity.setOppCityCode(getString(domain.getOppCityCode()));
		entity.setOppProdPackageID(getInteger(domain.getOppProdPackageID()));
		entity.setOppProdPackageName(getString(domain.getOppProdPackageName()));
		if (null == domain.getOppValue() || domain.getOppValue().compareTo(new BigDecimal(0)) <= 0) {
			entity.setOppValue(null);
		}

		entity.setOppCloseDate(getDate(domain.getOppCloseDateStamp()));
		entity.setOppWinRate(getInteger(domain.getOppWinRate()));

		entity.setModifiId(domain.getModifiId());
		entity.setModifitime(Calendar.getInstance().getTime());

		int r = -1;
		try {
			r = leadMapper.updateByPrimaryKey(entity);
		} catch (Exception e) {
			e.printStackTrace();
			r = -1;
		}

		if (r < 0) {
			result.setSuccess(false);
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, entity);
		return result;
	}

	public Integer getInteger(Integer value) {
		return isNumberInValid(value) ? null : value;
	}

	public String getString(String value) {
		return StringUtils.isEmpty(value) ? null : value;
	}

	public Date getDate(String timeStamp) {
		return StringUtils.isEmpty(timeStamp) ? null : new Date(Long.parseLong(timeStamp));
	}

	public ResultDO lose(LeadLoseDO domain) {

		MLeadLose entity = new MLeadLose();

		ResultDO result = BeanUtilsExtends.copy(entity, domain);

		if (!result.isSuccess()) {
			result.setSuccess(false);
			return result;
		}

		entity.setLookback(MemberConstant.LEAD_LOSE);
		entity.setIsDelete(MemberConstant.DB_ISDEL_NO);
		int r = -1;
		try {
			r = leadLoseMapper.insertSelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (r < 0) {
			result.setSuccess(false);
			return result;
		}

		r = -1;

		MLead entity2 = new MLead();

		entity2.setId(entity.getLeadID());
		entity2.setStatus(MemberConstant.LEAD_STATUS_LOSE); // 8 流失

		try {
			r = leadMapper.updateByPrimaryKeySelective(entity2);
		} catch (Exception e) {
			e.printStackTrace();
			r = -1;
		}

		if (r < 0) {
			result.setSuccess(false);
		}

		return result;
	}

	@Override
	public ResultDO loseBack(LeadDO domain) {

		ResultDO resultDO = modifi(domain);
		if (!resultDO.isSuccess()) {
			return resultDO;
		}

		MLeadLoseExample example = new MLeadLoseExample();
		MLeadLoseExample.Criteria criteria = example.createCriteria();
		criteria.andLeadIDEqualTo(domain.getId());
		criteria.andLookbackEqualTo(MemberConstant.LEAD_LOSE);

		MLeadLose entity = new MLeadLose();
		entity.setLookback(MemberConstant.LEAD_LOSE_BACK);
		leadLoseMapper.updateByExampleSelective(entity, example);

		return resultDO;
	}

	private MLead getEntity(MLead entity, LeadDO domain) {

		if (StringUtils.isNotEmpty(domain.getAlloTimeStamp())) {
			entity.setAlloTime(new Date(Long.parseLong(domain.getAlloTimeStamp())));
		}
		if (StringUtils.isNotEmpty(domain.getExpectdateStamp())) {
			entity.setExpectdate(new Date(Long.parseLong(domain.getExpectdateStamp())));
		}
		if (StringUtils.isNotEmpty(domain.getFollowNextStamp())) {
			entity.setFollowNext(new Date(Long.parseLong(domain.getFollowNextStamp())));
		}
		if (StringUtils.isNotEmpty(domain.getFollowTimeStamp())) {
			entity.setFollowTime(new Date(Long.parseLong(domain.getFollowTimeStamp())));
		}
		if (!isNumberInValid(domain.getCollectorEmployeeID())) {
			EmployeeDO em = employeeClientAPI.get(domain.getCollectorEmployeeID());
			entity.setCollectorEmployeeName(em.getRealName());
			entity.setCollectorMobile(em.getMobile());
		}
		return entity;
	}

	private String leadNo() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddssHHmmss");
		Calendar calendar = Calendar.getInstance();
		String dateName = dateFormat.format(calendar.getTime());
		int i = (int) (Math.random() * (999999 - 100000)) + 100000;
		dateName = dateName + "" + i;
		return dateName;
	}

	@Override
	public ResultDO get(Integer id) {

		MLead entity = null;

		ResultDO result = new ResultSupport();

		try {
			entity = leadMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (entity == null) {
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, getLeadInfo(entity));
		return result;
	}

	public ResultDO autoAllocation(LeadQueryDO query, Integer alloEmployeeID, String alloEmployeeName) {

		ResultDO result = query(query);

		List<LeadDO> listDO = (List<LeadDO>) result.getModel(ResultSupport.FIRST_MODEL_KEY);

		SchedulingQueryDO query2 = new SchedulingQueryDO();
		query2.setPage(false);
		query2.setSchedDateStamp(Calendar.getInstance().getTime() + "");
		ResultDO result2 = schedulingService.query(query2);

		List<SchedulingDO> listDO2 = (List<SchedulingDO>) result2.getModel(ResultSupport.FIRST_MODEL_KEY);

		int i = 0;
		Date alloTime = Calendar.getInstance().getTime();
		int leadSize = listDO.size();
		int schedulingSize = listDO2.size();
		if (leadSize > schedulingSize) {
			for (int s = 0; s < leadSize / schedulingSize; s++) {
				for (int p = 0; p < listDO2.size(); p++) {
					SchedulingDO schedulingDO = listDO2.get(p);
					for (; i < listDO.size(); i++) {
						LeadDO leadDO = listDO.get(i);
						MLead lead = new MLead();
						lead.setId(leadDO.getId());
						lead.setStatus(MemberConstant.LEAD_STATUS_TRACKINT);
						// 调度信息
						lead.setAlloEmployeeID(alloEmployeeID);
						lead.setAlloEmployeeName(alloEmployeeName);
						lead.setAlloTime(alloTime);
						// 分配人员信息
						lead.setSaleEmployeeId(schedulingDO.getEmployeeId());
						lead.setSaleName(schedulingDO.getEmployeeName());
						if (schedulingDO.getEmployeeId() != null) {
							EmployeeDO em = employeeClientAPI.get(schedulingDO.getEmployeeId());
							lead.setSaleName(em.getRealName());
							lead.setSaleMobile(em.getMobile());
							lead.setSaleOrgID(em.getOrgId());
						}
						try {
							leadMapper.updateByPrimaryKeySelective(lead);
						} catch (Exception e) {
							e.printStackTrace();
						}
						continue;
					}
				}
			}
		} else {
			for (int p = 0; p < listDO2.size(); p++) {
				SchedulingDO schedulingDO = listDO2.get(p);
				for (; i < listDO.size(); i++) {
					LeadDO leadDO = listDO.get(i);
					MLead lead = new MLead();
					lead.setId(leadDO.getId());
					lead.setSaleEmployeeId(schedulingDO.getEmployeeId());
					lead.setSaleName(schedulingDO.getEmployeeName());
					lead.setStatus(MemberConstant.LEAD_STATUS_TRACKINT);
					try {
						leadMapper.updateByPrimaryKeySelective(lead);
					} catch (Exception e) {
						e.printStackTrace();
					}
					continue;
				}
			}
		}

		return result;
	}

	@Override
	public ResultDO query(LeadQueryDO query) {

		ResultDO result = new ResultSupport();
		MLeadExample example = new MLeadExample();

		Criteria criteria = example.createCriteria();

		List<LeadDO> doList = null;

		if (StringUtils.isNotEmpty(query.getNameOrTel()) || StringUtils.isNotEmpty(query.getAddress())) {

			CustomerQueryDO query2 = new CustomerQueryDO();
			query2.setPage(false);
			if (StringUtils.isNotEmpty(query.getNameOrTel())) {
				query2.setNameOrTel(query.getNameOrTel());
			}
			if (StringUtils.isNotEmpty(query.getAddress())) {
				query2.setAddress(query.getAddress());
			}

			ResultDO res = customerService.query(query2);
			List<CustomerDO> list = (List<CustomerDO>) res.getModel(ResultDO.FIRST_MODEL_KEY);
			List<Integer> ids = new ArrayList<Integer>();
			for (CustomerDO data : list) {
				ids.add(data.getId());
			}
			criteria.andCustomerIdIn(ids);
		}

		if (StringUtils.isNotEmpty(query.getProvince())) {
			criteria.andProvinceEqualTo(query.getProvince());
		}
		if (StringUtils.isNotEmpty(query.getCity())) {
			criteria.andCityEqualTo(query.getCity());
		}
		if (StringUtils.isNotEmpty(query.getDistrict())) {
			criteria.andDistrictEqualTo(query.getDistrict());
		}
		if (StringUtils.isNotEmpty(query.getStartbirthday()) && StringUtils.isNotEmpty(query.getEndbirthday())) {
			Date startTime = new Date(Long.parseLong(query.getStartbirthday()));
			Date endTime = new Date((Long.parseLong(query.getEndbirthday()) + (24 * 60 * 60 * 1000)));
			criteria.andBirthdayBetween(startTime, endTime);
		}
		if (StringUtils.isNotEmpty(query.getBirthHospitalName())) {
			criteria.andBirthHospitalNameLike("%" + query.getBirthHospitalName() + "%");
		}
		if (query.getIsPhoto() != null && query.getIsPhoto() != 0) {
			criteria.andIsPhotoEqualTo(query.getIsPhoto());
		}
		if (!isNumberInValid(query.getChannelId())) {
			criteria.andChannelIDEqualTo(query.getChannelId());
		}
		if (query.getStatus() != null && query.getStatus() != 0) {
			// 未分配： status=1; 流失：status=8;
			criteria.andStatusEqualTo(query.getStatus());
		} else {
			// 业务跟踪(2-7)
			criteria.andStatusBetween(MemberConstant.LEAD_STATUS_NO_CONTACT, MemberConstant.LEAD_STATUS_DEAL);
		}
		if (!isNumberInValid(query.getSaleOrgId())) {
			criteria.andSaleOrgIDEqualTo(query.getSaleOrgId());
		}
		if (StringUtils.isNotEmpty(query.getSalesNameOrTel())) {
			if (query.getSalesNameOrTel() != null) {
				if (isChinaPhoneLegal(query.getNameOrTel())) {
					criteria.andSaleNameLike("%" + query.getSalesNameOrTel() + "%");
				} else {
					criteria.andSaleMobileLike("%" + query.getSalesNameOrTel() + "%");
				}
			}
		}
		if (StringUtils.isNotEmpty(query.getStartFollowNext()) && StringUtils.isNotEmpty(query.getEndFollowNext())) {
			Date startTime = new Date(Long.parseLong(query.getStartFollowNext()));
			Date endTime = new Date((Long.parseLong(query.getEndFollowNext()) + (24 * 60 * 60 * 1000)));
			criteria.andBirthdayBetween(startTime, endTime);
		}
		if (StringUtils.isNotEmpty(query.getCollectorNameOrTel())) {
			if (query.getCollectorNameOrTel() != null) {
				if (isChinaPhoneLegal(query.getCollectorNameOrTel())) {
					criteria.andCollectorEmployeeNameLike("%" + query.getCollectorNameOrTel() + "%");
				} else {
					criteria.andCollectorMobileLike("%" + query.getCollectorNameOrTel() + "%");
				}
			}
		}

		if (StringUtils.isNotEmpty(query.getStartCollectorTime())
				&& StringUtils.isNotEmpty(query.getEndCollectorTime())) {
			Date startTime = new Date(Long.parseLong(query.getStartCollectorTime()));
			Date endTime = new Date((Long.parseLong(query.getEndCollectorTime()) + (24 * 60 * 60 * 1000)));
			criteria.andCollectorTimeBetween(startTime, endTime);
		}
		if (StringUtils.isNotEmpty(query.getStartTime()) && StringUtils.isNotEmpty(query.getEndTime())) {
			Date startTime = new Date(Long.parseLong(query.getStartTime()));
			Date endTime = new Date((Long.parseLong(query.getEndTime()) + (24 * 60 * 60 * 1000)));
			criteria.andCreatetimeBetween(startTime, endTime);
		}

		if (StringUtils.isNotEmpty(query.getAuthorNameOrTel())) {
			if (query.getAuthorNameOrTel() != null) {
				if (isChinaPhoneLegal(query.getAuthorNameOrTel())) {
					criteria.andEmployeeNameLike("%" + query.getAuthorNameOrTel() + "%");
				} else {
					criteria.andEmployeeMobileLike("%" + query.getAuthorNameOrTel() + "%");
				}
			}
		}
		criteria.andIsDeleteEqualTo(MemberConstant.DB_ISDEL_NO);

		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = leadMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}

		List<MLead> list = null;

		try {
			list = leadMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "获取线索信息失败");
			result.setSuccess(false);
			return result;
		}

		doList = getLeadDOList(list);

		if (doList == null) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG + "填充数据失败");
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, doList);

		return result;

	}

	public LeadDO getLeadInfo(MLead entity) {
		LeadDO leadDO = getLeadDO(entity);
		if (leadDO == null) {
			return null;
		}
		if (entity.getBirthHospital() != null)
			leadDO.setBirthHospitalName(getChannelName(entity.getBirthHospital()));

		if (entity.getChannelTypeID() != null)
			leadDO.setChannelTypeName(getChannelTypeName(entity.getChannelTypeID()));

		if (entity.getChannelID() != null)
			leadDO.setChannelName(getChannelName(entity.getChannelID()));

		if (entity.getWindowID() != null)
			leadDO.setWindowName(getChannelWindow(entity.getWindowID()));

		if (entity.getAlloTime() != null)
			leadDO.setAlloTimeStamp(entity.getAlloTime().getTime() + "");

		if (entity.getExpectdate() != null)
			leadDO.setExpectdateStamp(entity.getExpectdate().getTime() + "");

		if (entity.getCreatetime() != null)
			leadDO.setCreateTimeName(entity.getCreatetime().getTime() + "");

		if (entity.getModifitime() != null)
			leadDO.setModifiTimeName(entity.getModifitime().getTime() + "");

		if (entity.getFollowTime() != null)
			leadDO.setFollowTimeStamp(entity.getFollowTime().getTime() + "");

		if (entity.getFollowNext() != null)
			leadDO.setFollowNextStamp(entity.getFollowNext().getTime() + "");

		if (entity.getCollectorTime() != null)
			leadDO.setCollectorTimeStamp(entity.getCollectorTime().getTime() + "");

		if (entity.getOppCloseDate() != null)
			leadDO.setOppCloseDateStamp(entity.getOppCloseDate().getTime() + "");
		// 客户信息
		ResultDO resultDO = customerService.get(entity.getCustomerId());
		if (resultDO.isSuccess()) {
			Map<String, Object> map = (Map<String, Object>) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);
			if (null != map) {
				CustomerDO customerDO = (CustomerDO) map.get("customerDO");
				leadDO.setCustomerDO(customerDO);
			}
		}
		// 照片原因
		if (null != entity.getIsPhoto() && entity.getIsPhoto() == 0 && !isNumberInValid(entity.getNotPhotoReason())) {
			DictionariesDO dicDO = dicClientAPI.get(entity.getNotPhotoReason());
			if (dicDO != null) {
				leadDO.setNotPhotoReasonName(dicDO.getDataItem());
			}
		}

		// 业务类型
		if (entity.getBusinessType() == MemberConstant.LEAD_BUSINESS_GRAVIDA) {
			ResultDO res = customerFamilyService.get(entity.getBusinessFamilyID());
			CustomerFamilyDO familyDO = (CustomerFamilyDO) res.getModel(ResultDO.FIRST_MODEL_KEY);
			leadDO.setBirthdayStamp(familyDO.getBirthdayStamp());
			leadDO.setBusinessFamily(familyDO);
			leadDO.setBusinessTypeName("孕妈照");
		} else {
			ResultDO res = customerFamilyService.get(entity.getBusinessFamilyID());
			CustomerFamilyDO familyDO = (CustomerFamilyDO) res.getModel(ResultDO.FIRST_MODEL_KEY);
			leadDO.setBirthdayStamp(familyDO.getBirthdayStamp());
			leadDO.setBusinessFamily(familyDO);
			if (entity.getBusinessType() == MemberConstant.LEAD_BUSINESS_CHILDREN) {
				leadDO.setBusinessTypeName("儿童照");
			} else {
				leadDO.setBusinessTypeName("婴儿照");
			}
		}

		// 转介绍分类
		if (entity.getIntrodType() != null) {
			// 介绍人:1-客户；2-员工
			leadDO.setIntrodTypeName((entity.getIntrodType() == 1) ? "客户" : "员工");
		}

		// 1-新收集;2-未联系上;3-跟进中;4-预订成功;5-预订改期;6-预订取消;7-成交;8-流失
		if (entity.getStatus() != null) {
			leadDO.setStatusName(StaticDicUtil.STATUS_LEAD.get(entity.getStatus()));

			// 流失原因
			if (entity.getStatus() == MemberConstant.LEAD_STATUS_LOSE) {
				leadDO.setLoseReasonName(getLoseReason(entity.getId()));
			}
		}

		// 赢单概率
		if (!isNumberInValid(entity.getOppWinRate())) {
			DictionariesDO dicDO = dicClientAPI.get(entity.getOppWinRate());
			if (dicDO != null) {
				leadDO.setOppWinRateStr(dicDO.getDataItem());
			}
		}

		// 最近跟进记录
		SaleContactRecordQueryDO query = new SaleContactRecordQueryDO();
		query.setLeadId(leadDO.getId());
		query.setPage(false);
		ResultDO resultDO2 = salesRecordService.getLatestRecord(query);
		if (resultDO2.isSuccess()) {
			SaleContactRecordDO recordDO = (SaleContactRecordDO) resultDO2.getModel(ResultDO.FIRST_MODEL_KEY);
			leadDO.setRecordDateStamp(recordDO.getCreateTimeName());
			leadDO.setRecordRemark(recordDO.getRemark());
			if (StringUtils.isNotEmpty(recordDO.getNextDateStamp())) {
				leadDO.setFollowNextStamp(recordDO.getNextDateStamp());
			}
		}

		return leadDO;
	}

	public String getDicItem(Integer id) {
		DictionariesDO dicDO = dicClientAPI.get(id);
		return dicDO == null ? null : dicDO.getDataItem();
	}

	public String getChannelName(Integer id) {
		ChannelDO channelDO = channelClientAPI.getChannel(id);
		return channelDO == null ? null : channelDO.getChannelName();
	}

	public String getChannelTypeName(Integer id) {
		ChannelTypeDO channelTypeDO = channelClientAPI.getChannelType(id);
		return channelTypeDO == null ? null : channelTypeDO.getChannelName();

	}

	public String getChannelWindow(Integer id) {
		ChannelWindowDO channelWindowDO = channelClientAPI.getChannelWindow(id);
		return channelWindowDO == null ? null : channelWindowDO.getWindowName();

	}

	/**
	 * 对象拷贝单个实体到对象中
	 * 
	 * @param obj
	 * @return 返回DO对象
	 */
	public LeadDO getLeadDO(MLead entity) {
		LeadDO dst = new LeadDO();
		if (entity == null)
			return null;
		return BeanUtilsExtends.copyProperties(dst, entity) ? dst : null;
	}

	/**
	 * 对象拷贝多个实体到列表中
	 * 
	 * @param List
	 * @return List
	 */
	public List<LeadDO> getLeadDOList(List<MLead> list) {
		List<LeadDO> result = new ArrayList<LeadDO>();
		if (list != null && !list.isEmpty()) {
			for (MLead entity : list) {
				LeadDO domain = getLeadInfo(entity);
				if (domain != null) {
					result.add(domain);
				}
			}
		}
		return result;
	}

	@Override
	public ResultDO updateFollow(Integer id, Integer status, Date followTime, Date followNext) {

		ResultDO result = new ResultSupport();

		MLead entity = new MLead();
		entity.setId(id);
		entity.setStatus(status);
		// 最近跟进时间
		if (followTime != null) {
			entity.setFollowTime(followTime);
		}
		// 下次更近日期
		entity.setFollowNext(followNext);
		int ret = leadMapper.updateByPrimaryKeySelective(entity);
		if (ret < 1) {
			result.setSuccess(false);
		}

		return result;
	}

	public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
		String regExp = "^((13[0-9])|(14[5-9]|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8,9])))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	@Override
	public ResultDO allocation(LeadDO domain) {

		ResultDO result = new ResultSupport();
		Integer[] ids = domain.getIds();

		for (Integer id : ids) {
			try {
				MLead entity = leadMapper.selectByPrimaryKey(id);
				if (entity == null) {
					result.setSuccess(false);
					return result;
				}
				entity.setAlloEmployeeID(domain.getAlloEmployeeID());
				EmployeeDO alloEmdo = employeeClientAPI.get(domain.getAlloEmployeeID());
				if (alloEmdo == null) {
					result.setSuccess(false);
					return result;
				}
				entity.setAlloEmployeeName(alloEmdo.getRealName());
				entity.setAlloTime(Calendar.getInstance().getTime());
				entity.setSaleEmployeeId(domain.getSaleEmployeeId());

				EmployeeDO edo = employeeClientAPI.get(domain.getSaleEmployeeId());

				if (edo == null) {
					result.setSuccess(false);
					return result;
				}

				entity.setSaleName(edo.getRealName());
				entity.setSaleMobile(edo.getMobile());
				entity.setStatus(MemberConstant.LEAD_STATUS_TRACKINT);
				leadMapper.updateByPrimaryKeySelective(entity);

				// 写入跟踪记录表
				SaleContactRecordDO recordDO = new SaleContactRecordDO();
				recordDO.setLeadId(entity.getId());
				recordDO.setCustomerId(entity.getCustomerId());
				// recordDO.setContactId(entity.getCustomerFamilyId());
				recordDO.setEmployeeId(entity.getAlloEmployeeID());
				recordDO.setEmployeeName(entity.getAlloEmployeeName());
				recordDO.setTopic("分配线索");
				recordDO.setRemark("");
				recordDO.setNextDateStamp(domain.getFollowNextStamp());
				salesRecordService.add(recordDO);

			} catch (Exception e) {
				e.printStackTrace();
				result.setSuccess(false);
				break;
			}
		}

		return result;
	}

	public String getLoseReason(Integer leadId) {
		MLeadLoseExample example = new MLeadLoseExample();
		MLeadLoseExample.Criteria criteria = example.createCriteria();
		criteria.andLeadIDEqualTo(leadId);
		criteria.andLookbackEqualTo(MemberConstant.LEAD_LOSE);
		criteria.andIsDeleteEqualTo(MemberConstant.DB_ISDEL_NO);
		example.setOrderByClause(" id desc ");
		List<MLeadLose> list = leadLoseMapper.selectByExample(example);
		if (null != list && list.size() > 0) {
			Integer loseReason = list.get(0).getLoseReason();
			if (isNumberInValid(loseReason)) {
				return null;
			}
			DictionariesDO dictionariesDO = dicClientAPI.get(loseReason);
			return dictionariesDO == null ? null : dictionariesDO.getDataItem();
		}
		return null;
	}

}
